import drag from '@/components/TableDrag/drag'
import { Tp_applysourceList } from '@/enumeration/Tp_applysource'
import { LableTitle } from '@/enumeration/LableTitle.js'
import { Tp_biztype } from '@/enumeration/Tp_biztype'
import { APP_USER, APP_DEPT } from '@/store/mutation-types.js'
import storage from 'store'
import moment from 'moment'
import CommonHeadQueryComponent from '@/views/accept/component/CommonHeadQueryComponent.vue'
import CommonHeaderComponent from '@/views/accept/component/CommonHeaderComponent.vue'
import { queryMf_MyTaskUndoList } from '@/api/workflow/mf_MyTaskUndo.js'
import { updateFirstAndSecondPerson } from '@/api/supervise/apl_supervise.js'
import { processNext } from '@/api/workflow/mf_MyTaskDone'
import { taskExec } from '@/api/workflow/mf_MyTaskUndo'
export const SuperviseCommonMinxin = {
  data () {
    return {
      ucolumns: [],
      doneUcolumns: [],
      undoNeedDealNum: undefined,
      doneDealNum: undefined,
      allDealNum: undefined,
      queryParam: {
        acceptcode: '', // 案号
        applyname: '', // 申请人
        targetname: '', // 被申请人
        applyStartDate: null, // 开始时间
        applyEndDate: null, // 结束时间
        source: undefined, // 来源
        pageNumber: 1,
        pageSize: 20,
        order: 'desc',
        userid: '', // 用户id
        state: '1',
        bizenum: null,
        matid: null,
        departid: null, // 部门
        category: undefined, // 环节标识
        categorynone: null, // 不相同的环节标识
        statusapply: []
      },
      listData: [], // 待处理
      doneListData: [], // 已处理
      allListData: [], // 全部案件
      upagination: {
        // 表格分页参数
        defaultPageSize: 20,
        total: 0,
        current: 1,
        pageSize: 20,
        showTotal: (total) => `共计 ${total} 条数据`,
        showSizeChanger: true,
        showQuickJumper: true,
        pageSizeOptions: ['10', '20', '50', '100']
      },
      loading: false,
      ubordered: true, // 表格边框是否显示
      mixins: [drag],
      Tp_applysourceList: Tp_applysourceList,
      Tp_biztype: Tp_biztype,
      currentUser: storage.get(APP_USER), // 登录人信息
      currentDept: storage.get(APP_DEPT), // 登录人部门
      LableTitle: LableTitle,
      header: undefined,
      tableCountKey: 0,
      collapseKey: [1], // 折叠面板key

      isEntrustModel: false, // 分派任务树
      applyid: null,
      assignData: {
        taskid: null, // 当前分派任务的taskid
        firstUserid: null, // 主办人userid
        firstUsername: null, // 主办人username
        secondUserid: null, // 协办人userid
        secondUsername: null // 协办人userid
      },
      selectData: {},
      assignType: 0, // 分派模式：0：单个分派，1：批量勾选分派

      rowSelection: {
        type: 'checkbox',
        // 不使用箭头函数就无法获取this
        // 单选
        onSelect: (record, selected, selectedRows, nativeEvent) => {
          // console.log(record, selected, selectedRows, nativeEvent)
          const list = this.rowSelection.selectRowList
          const selectedRowKeys = this.rowSelection.selectedRowKeys
          console.log(list, selectedRowKeys)
          if (!selected) {
            // 这里是取消勾选，删除对应的数组项
            selectedRowKeys.map((x, key) => {
              if (x === record.id) {
                selectedRowKeys.splice(key, 1)
              }
            })
            list.map((x, key) => {
              if (x.id === record.id) {
                list.splice(key, 1)
              }
            })
            console.log(this.rowSelection.selectedRowKeys)
          }
          if (selected) {
            // 这里是点击勾选，添加workerId字段到selectedRowKeys数组里
            this.rowSelection.selectedRowKeys.push(record.id)
            this.rowSelection.selectRowList.push(record)
            console.log(this.rowSelection.selectedRowKeys)
          }
        },
        // 全选
        onSelectAll: (selected, selectedRows, changeRows) => {
          console.log(selected, selectedRows, changeRows)
          if (selected) {
            changeRows.map((x) => {
              this.rowSelection.selectedRowKeys.push(x.id)
              this.rowSelection.selectRowList.push(x)
            })
          }
          if (!selected) {
            const list = this.rowSelection.selectRowList
            const selectedRowKeys = this.rowSelection.selectedRowKeys
            changeRows.map((item, k) => {
              selectedRowKeys.map((x, key) => {
                if (x === item.id) {
                  selectedRowKeys.splice(key, 1)
                }
              })
              list.map((x, key) => {
                if (x.id === item.id) {
                  list.splice(key, 1)
                }
              })
            })
            this.rowSelection.selectRowList = list
            this.rowSelection.selectedRowKeys = selectedRowKeys
          }
        },
        selectedRowKeys: [],
        selectRowList: []
      },
      confirmLoading: false,
      scroll: { x: 1000, y: 410 }
    }
  },
  components: {
    deptUserTree: () => import('@/views/base/DeptUserTree.vue'),
    CommonHeadQueryComponent,
    CommonHeaderComponent
  },
  watch: {
    ucolumns: {
      handler (newValue, oldVal) {
        this.headerChange()
      },
      deep: true // 深度监听
    }
  },
  methods: {
    headerChange () {
      console.log('移动后', this.ucolumns)
      this.header = {
        header: {
          cell: drag.methods.initDrag(this.ucolumns)
        }
      }
    },
    setColumns (columns) {
      console.log('重置前', this.ucolumns)
      // tableCountKey自增是为了让表格控件每次销毁强制更新
      this.tableCountKey += 1
      this.ucolumns = columns
      // this.ucolumns = columns
      console.log('重置后', this.ucolumns)
    },

    /**
     * 显示处理界面
     */
    showHand (record, pattern) {
      this.$router.push({
        path: `/SuperviseTodoOpearation/${record.taskid}/${pattern}`,
        query: {
          url: '/SuperviseTodo',
          queryParam: record
        }
      })
    },

    tableChange (upagination, filters, sorter, { currentDataSource }) {
      this.row_idx = upagination.current * upagination.pageSize - upagination.pageSize
      this.queryParam.pageNumber = upagination.current
      this.queryParam.pageSize = upagination.pageSize
      this.queryList()
    },
    /**
     * 初始化设置默认值
     */
    initDefaultParam () {
      this.queryParam.userid = this.currentUser.userId
      this.queryParam.bizenum = this.Tp_biztype['supervise'].value
      this.queryParam.matid = '100000_360100-000201005000-QT-002-02'
      this.queryParam.categorynone = 'assignment'
    },
    onSearch (val) {
      this.queryParam.acceptcode = val
      this.queryParam.pageNumber = 1
      this.queryParam.pageSize = 20
      this.queryUndoTaskList()
    },
    /**
     * 重置查询条件并查询数据
     */
    reQuery () {
      this.queryParam = {
        acceptcode: '', // 案号
        applyname: '', // 申请人
        targetname: '', // 被申请人
        applyStartDate: null, // 开始时间
        applyEndDate: null, // 结束时间
        source: undefined, // 来源
        pageNumber: 1,
        pageSize: 20,
        order: 'desc',
        userid: '', // 用户id
        state: '1',
        bizenum: null,
        matid: null,
        departid: null, // 部门id
        category: undefined, // 环节标识
        categorynone: null, // 不相同的环节标识
        statusapply: []
      }
      this.initDefaultParam()
      this.queryUndoTaskList()
    },
    queryUndoTaskList () {
      this.queryList()
    },

    getCpQueryParam () {
      // 时间转换
      const cpQueryParam = JSON.parse(JSON.stringify(this.queryParam))
      if (this.queryParam.applyStartDate?.format) {
        cpQueryParam.applyStartDate = this.queryParam.applyStartDate.format('YYYY-MM-DD') + ' 00:00:00'
      }
      if (this.queryParam.applyEndDate?.format) {
        cpQueryParam.applyEndDate = this.queryParam.applyEndDate.format('YYYY-MM-DD') + ' 23:59:59'
      }
      return cpQueryParam
    },

    queryList () {
      const queryParam = this.getCpQueryParam()
      if (queryParam.acceptcode) {
        queryParam.acceptcode = queryParam.acceptcode.toString().trim()
      }
      if (queryParam.targetname) {
        queryParam.targetname = queryParam.targetname.toString().trim()
      }
      if (queryParam.applyname) {
        queryParam.applyname = queryParam.applyname.toString().trim()
      }
      this.loading = true
      queryMf_MyTaskUndoList({ userid: queryParam.userid }, queryParam)
        .then((res) => {
          if (res.code !== 0) {
            this.$message.error('获取数据失败')
          } else {
            this.listData = res.data.records
            this.upagination.total = res.data.total
            this.upagination.current = res.data.current
            this.upagination.pageSize = res.data.size
            this.undoNeedDealNum = res.data.total
            this.setEnumData(this.listData)
          }
        })
        .catch((err) => {
          this.listData = []
          console.log(err, '获取数据失败')
        })
        .finally(() => {
          this.loading = false
        })
    },

    // 设置对应的枚举值
    setEnumData (listData) {
      if (listData && listData.length > 0) {
        for (var index = 0; index < listData.length; index++) {
          const item = listData[index]
          if (item) {
            // 被申请人名称
            item.targetname_text = item.targetname
            // 来源
            item.source_text = this.sourceLable(item.source)
            // 承办人
            let dealNames = []
            dealNames.push(item.firstname || item.firstname_bs)
            dealNames.push(item.secondname || item.secondname_bs)
            dealNames = dealNames.filter(el => (el != null && el != ''))
            item.dealName = dealNames.join(',')
          }
        }
      }
    },
    // 来源转换显示
    sourceLable (val) {
      for (const key in this.Tp_applysourceList) {
        if (this.Tp_applysourceList[key].value == val) {
          return this.Tp_applysourceList[key].name
        }
      }
      return val
    },
    //
    rowClassName (record, index) {
      return index % 2 === 0 ? 'oddRow' : 'evenRow'
    },
    // 一键分派
    onekeyAssign () {
      const selectedRows = this.rowSelection.selectRowList
      this.assignType = 1
      if (selectedRows && selectedRows.length > 0) {
        this.isEntrustModel = true
      } else {
        this.$message.warning('请勾选一条数据')
      }
    },
    // 分派任务
    showAssign (record) {
      this.assignData.taskid = record.taskid
      this.applyid = record.applyid
      this.assignType = 0
      this.isEntrustModel = true
      this.selectData = record
    },
    // 主办人保存
    async firstTreeSave (obj) {
      // console.log('主办人', obj)
      if (obj.id) {
        if (obj.id == this.assignData.secondUserid) {
          this.$message.warning('主办人不能和承办人为同一个人')
          this.$refs.firstTreeRef.clearForm()
          return
        }
        this.assignData.firstUserid = obj.id
        this.assignData.firstUsername = obj.name
      } else {
        this.assignData.firstUserid = null
        this.assignData.firstUsername = null
      }
    },
    // 协办人保存
    async secondTreeSave (obj) {
      // console.log('协办人', obj)
      if (obj.id) {
        if (obj.id == this.assignData.firstUserid) {
          this.$message.warning('主办人不能和承办人为同一个人')
          this.$refs.secondTreeRef.clearForm()
          return
        }
        this.assignData.secondUserid = obj.id
        this.assignData.secondUsername = obj.name
      } else {
        this.assignData.secondUserid = null
        this.assignData.secondUsername = null
      }
    },
    // 确认分派
    async saveAssign () {
      const selectedRows = this.rowSelection.selectRowList
      if (!selectedRows || selectedRows.length < 0) {
        this.$message.warning('请勾选一条数据')
        return
      }
      if (!this.assignData.firstUserid) {
        this.$message.warning('请选择主办人')
        return
      }
      if (!this.assignData.secondUserid) {
        this.$message.warning('请选择协办人')
        return
      }
      // 1. 保存第一第二审查人信息
      let ids = []
      let taskids = []
      if (this.assignType === 0) {
        // 单个分派
        ids.push(this.applyid)
        taskids.push(this.assignData.taskid)
      } else {
        ids = selectedRows.map((data) => data.applyid)
        taskids = selectedRows.map((data) => data.taskid)
      }
      const savem = this.$message.loading('正在分派中...', 0)
      this.confirmLoading = true
      const res = await updateFirstAndSecondPerson(
        ids,
        this.assignData.firstUserid,
        this.assignData.firstUsername,
        this.assignData.secondUserid,
        this.assignData.secondUsername,
        this.currentDept.id
      )
      if (res.code == 0) {
          // 2、完结当前的分派环节的任务
          new Promise((resolve) => {
            this.listData.forEach(async el => {
              // 调用分派接口
              const tempTaskId = el.taskid
              if (taskids.includes(tempTaskId)) {
                const variables = {
                  'firstid': this.assignData.firstUserid
                }
                const processNextExecutor = {
                  variable: variables,
                  taskFrom: {},
                  applyid: el.applyid,
                  handletext: '案件分派',
                  remark: '案件分派'
                }
                const params = {
                  formid: el.formid,
                  taskid: tempTaskId,
                  // 完成人员
                  userid: this.currentUser.userId
                }
                const res1 = await taskExec(params, processNextExecutor)
                if (res1.code == 0) {
                  this.$message.success('操作成功')
                  this.isEntrustModel = false
                }
                resolve()
              }
            })
          }).then(() => {
            this.queryUndoTaskList()
          }).finally(() => {
            this.confirmLoading = false
            setTimeout(savem, 0)
          })
      } else {
        this.$message.error('案件分派人员失败')
      }
    }
  }
}
